package co.salehi.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import co.salehi.domain.Cart;
import co.salehi.domain.Tyre;

@RooWebScaffold(path = "tyres", formBackingObject = Tyre.class)
@RequestMapping("/tyres")
@Controller
public class TyreController {

	@RequestMapping(params = { "addToCart", "selectedItems" }, method = RequestMethod.GET)
	public String addToCart(Model uiModel, HttpServletRequest request) {

		String str = request.getParameter("selectedItems");

		Cart sessionCart = request.getSession().getAttribute("cart") == null ? new Cart()
				: (Cart) request.getSession().getAttribute("cart");

		for (String idStr : str.split(",")) {
			sessionCart.getTyreIds().add(Long.parseLong(idStr));
		}

		request.getSession().setAttribute("cart", sessionCart);

		return "tyres/list";
	}

	@RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model uiModel) {
		uiModel.addAttribute("tyre", Tyre.findTyre(id));
		addDateTimeFormatPatterns(uiModel);
		return "tyres/update";
	}

	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public String delete(@PathVariable("id") Long id,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size,
			Model uiModel) {
		Tyre.findTyre(id).remove();
		uiModel.asMap().clear();
		uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
		uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
		return "redirect:/tyres";
	}
	
	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	@RequestMapping(method = RequestMethod.GET, params={"soldouts"})
    public String listSolds(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            uiModel.addAttribute("tyres", Tyre.findSoldTyreEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));
            float nrOfPages = (float) Tyre.countSoldTyres() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("tyres", Tyre.findAllSoldTyres());
        }
        addDateTimeFormatPatterns(uiModel);
        return "tyres/listSolds";
    }
	
	@PreAuthorize("hasAuthority('ROLE_ADMIN')")
	@RequestMapping(params = { "unsell", "selectedItems" }, method = RequestMethod.GET)
	public String unsell(Model uiModel, HttpServletRequest request) {

		String str = request.getParameter("selectedItems");


		for (String idStr : str.split(",")) {
			Tyre tyre = Tyre.findTyre(Long.parseLong(idStr)); 
			tyre.setSellDate(null);
			tyre.merge();
		}

		uiModel.addAttribute("soldouts", true);
		return "tyres/listSolds";
	}

	
}
